import 'package:base_lib/common/base/base_theme_state.dart';
import 'package:base_lib/common/index.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/theme/theme_global.dart';
import 'package:doctor_login_lib/repository/http.dart';
import 'package:doctor_prescribe_lib/doctor_prescribe_component.dart';
import 'package:doctor_prescribe_lib/offline/basic_info/bloc.dart';
import 'package:doctor_prescribe_lib/prescribe_util.dart';
import 'package:doctor_prescribe_lib/repository/http.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:doctor_login_lib/entity/get_org_info_entity.dart'
    as GetOrgInfoBean;
import 'entity/rp_detail_entity.dart' as RpDetailBean;

///处方-订单详情
class RpOrderPage extends StatefulWidget {
  final Parameters parameters;

  RpOrderPage(this.parameters);

  @override
  State<StatefulWidget> createState() {
    return _State();
  }
}

class _TransWay {
  String des;
  int code;

  _TransWay(this.des, this.code);
}

class _State extends BaseThemeState<RpOrderPage> {
  var tsGrey = TextStyle(color: Colors.grey, fontSize: 14);
  var tsBlack = TextStyle(color: Colors.black, fontSize: 14);
  var tsBigBlack =
      TextStyle(color: Colors.black, fontSize: 16, fontWeight: FontWeight.bold);

  // 0:上门自取
  // 1:送货上门
  // 2:快递
  List<_TransWay> transWayList = [
    _TransWay('物流配送', 2),
    _TransWay('送货上门', 1),
    _TransWay('上门自取', 0)
  ];

  _TransWay _transWay;

  String patientAddress;
  GetOrgInfoBean.Data orgInfo;

  RpDetailBean.Data rp;

  String remark = '';

  @override
  void initState() {
    super.initState();
    _transWay = transWayList.last;
    try {
      patientAddress =
          '${OfflineBasicInfoBloc.basicInfoData.patient.province} ${OfflineBasicInfoBloc.basicInfoData.patient.city} ${OfflineBasicInfoBloc.basicInfoData.patient.area} ${OfflineBasicInfoBloc.basicInfoData.patient.address}';
    } catch (e) {
      print(e);
      patientAddress = '';
    }
    getRpInfo();
  }

  @override
  Widget buildChild(BuildContext context, MTheme theme) {
    return Scaffold(
      appBar: AppBar(
        leading: BackButton(
          onPressed: () {
            Routers.pop(context);
          },
        ),
        centerTitle: true,
        title: Text('订单详情'),
      ),
      body: LayoutBuilder(
        builder: (context, cons) {
          return rp == null || orgInfo == null
              ? buildLoadingIndicator()
              : Container(
                  constraints: cons,
                  color: theme.themeColor.themeBgColor,
                  child: Column(
                    children: [
                      Expanded(
                          child: SingleChildScrollView(
                        child: Column(
                          children: [
                            20.vGapDp,
                            _buildMedicineList(theme),
                            20.vGapDp,
                            _buildTransitionWay(theme),
                            1.vGapDp,
                            buildRemark(theme),
                            1.vGapDp,
                            Container(
                              color: Colors.white,
                              padding: EdgeInsets.symmetric(
                                  horizontal: 10, vertical: 15),
                              child: Row(
                                children: [
                                  Text(
                                    '商品金额',
                                    style: tsBigBlack,
                                  ),
                                  Spacer(),
                                  Text(
                                    '¥${PrescribeUtil.formatMoneyForSumShow(rp.recipeAllPrice)}',
                                    style: tsBlack,
                                  )
                                ],
                              ),
                            ),
                            _transWay.code == 1
                                ? Container(
                                    color: Colors.white,
                                    padding: EdgeInsets.only(
                                        left: 10, right: 10, bottom: 15),
                                    child: Row(
                                      children: [
                                        Text(
                                          '运费',
                                          style: tsBigBlack,
                                        ),
                                        Spacer(),
                                        Text(
                                          '免费',
                                          style: tsBlack,
                                        )
                                      ],
                                    ),
                                  )
                                : SizedBox(),
                          ],
                        ),
                      )),
                      Container(
                        width: double.infinity,
                        color: Colors.white,
                        padding:
                            EdgeInsets.symmetric(horizontal: 50, vertical: 25),
                        child: FlatButton(
                          onPressed: () {},
                          color: theme.themeColor.themeColor,
                          child: Text(
                            '代付',
                            style: tsBlack.copyWith(color: Colors.white),
                          ),
                        ),
                      ),
                    ],
                  ),
                );
        },
      ),
    );
  }

  ///药品列表
  _buildMedicineList(MTheme theme) {
    if (rp.rpTypeID == 0) {
      //西药
      return Container(
        color: Colors.white,
        padding: EdgeInsets.all(10),
        child: Column(
          children: rp.medicines.map((e) {
            return Column(
              children: [
                Row(
                  children: [
                    Expanded(
                        child: Text(
                      e.medicineName,
                      style: tsBlack.copyWith(fontWeight: FontWeight.bold),
                    )),
                    Text(
                      "￥${PrescribeUtil.formatMoney(e.unitPrice)}",
                      style: tsBlack.copyWith(color: Colors.red),
                    )
                  ],
                ),
                5.vGapDp,
                Row(
                  children: [
                    Expanded(
                        child: Text(
                      '用法用量：${e.takeDose}${e.formType}/次，${e.takeFrequence},${e.takeDirection}',
                      style: tsGrey,
                    )),
                    Text(
                      "x ${e.medicineAmount}",
                      style: tsGrey,
                    )
                  ],
                ),
                8.vGapDp,
                DottedLine(color: Colors.grey[300], dashWidth: 2),
              ],
            );
          }).toList(),
        ),
      );
    } else if (rp.rpTypeID == 1) {
      //中药
      String medicinesStr = '';
      rp.medicines.forEach((e) {
        medicinesStr +=
            '${e.medicineName} ${e.medicineAmount}g （${e.takeDirection}）    ';
      });

      medicinesStr +=
          "${rp.medicineFormID == 10 ? '[饮片]' : rp.medicineFormID == 11 ? '[颗粒剂]' : ''}";

      return Container(
        color: Colors.white,
        padding: EdgeInsets.all(10),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text(
            medicinesStr,
            style: tsBlack,
          ),
          15.vGapDp,
          DottedLine(color: Colors.grey[300], dashWidth: 2),
          15.vGapDp,
          Text(
            '用法用量',
            style: tsBigBlack,
          ),
          15.vGapDp,
          Text(
              '${rp.chineseMedicine.direction}，\n共${rp.totalDoses}剂，每日${rp.chineseMedicine.frequence}剂，分${rp.chineseMedicine.everyDose}次服用。',
              style: tsBlack),
          15.vGapDp,
          DottedLine(color: Colors.grey[300], dashWidth: 2),
          15.vGapDp,
          Text(
            '医嘱提醒',
            style: tsBigBlack,
          ),
          Container(
            alignment: Alignment.topLeft,
            width: double.infinity,
            padding: EdgeInsets.only(left: 15,right: 15,top: 10,bottom: 20),
            margin: EdgeInsets.all(10),
            decoration: BoxDecoration(color: Colors.grey[200],borderRadius: BorderRadius.circular(8)),
            child: Text(rp.enjoin),
          ),
        ]),
      );
    } else {
      return SizedBox();
    }
  }

  ///配送方式
  _buildTransitionWay(MTheme theme) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 10),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                  child: Text(
                '配送方式',
                style: tsBigBlack,
              )),
              FlatButton(
                  padding: EdgeInsets.zero,
                  onPressed: () async {
                    FocusScope.of(context).unfocus();
                    WPicker.showWPicker<_TransWay>(
                            context: context,
                            itemList: transWayList,
                            map2string: (e) => e.des,
                            selectedItem: _transWay)
                        .then((value) {
                      if (value != null) {
                        _transWay = value;
                        doRefresh();
                      }
                    });
                  },
                  child: Row(
                    children: [
                      Icon(
                        Icons.keyboard_arrow_down_outlined,
                        color: Colors.grey,
                        size: 20,
                      ),
                      Text(
                        _transWay.des,
                        style: tsBlack,
                      )
                    ],
                  ))
            ],
          ),
          10.vGapDp,
          _transWay.code == 0
              ? Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      orgInfo.orgName,
                      textAlign: TextAlign.start,
                      style: tsBlack,
                    ),
                    10.vGapDp,
                    Text(
                      '${orgInfo.province} ${orgInfo.city} ${orgInfo.area} ${orgInfo.address}',
                      textAlign: TextAlign.start,
                      style: tsBlack,
                    ),
                  ],
                )
              : Row(
                  children: [
                    Expanded(
                        child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '${rp.patientInfo.patientName}  ${rp.patientInfo.patientPhone}',
                          style: tsBlack,
                        ),
                        10.vGapDp,
                        Text(
                          patientAddress,
                          style: tsBlack,
                        ),
                      ],
                    )),
                    IconButton(
                        icon: Icon(Icons.arrow_forward_ios_rounded),
                        iconSize: 20,
                        color: Colors.grey,
                        onPressed: () {
                          FocusScope.of(context).unfocus();
                          Routers.navigateTo(
                                  context,
                                  DoctorPrescribeComponent
                                      .editShippingAddressPage,
                                  parameters: Parameters()
                                    ..putObj('info', rp.patientInfo))
                              .then((value) {
                            if (value is RpDetailBean.PatientInfo) {
                              rp.patientInfo = value;
                              doRefresh();
                            }
                          });
                        })
                  ],
                ),
          15.vGapDp,
        ],
      ),
    );
  }

  ///备注
  buildRemark(MTheme theme) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(10),
      child: Row(
        children: [
          Text(
            '备注：',
            style: tsBigBlack,
          ),
          8.hGapDp,
          Expanded(
              child: Container(
            padding: EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: Colors.grey[200],
              borderRadius: BorderRadius.circular(15),
            ),
            child: TextField(
              decoration: InputDecoration(
                  border: InputBorder.none,
                  hintStyle: tsGrey,
                  hintText: '选填，可填写和商家达成一致的要求'),
              maxLines: 3,
              maxLength: 100,
              onChanged: (str) {
                remark = str;
              },
            ),
          ))
        ],
      ),
    );
  }

  /// 获取机构信息
  getOrgInfo(String orgID) async {
    var result = await LoginHttp.getOrgInfos([orgID]);
    if (result.isSuccess) {
      orgInfo = result.data.first;
      doRefresh();
    } else {
      ToastUtil.error('获取机构信息出错！' + result.error.msg);
      Routers.pop(context);
    }
  }

  /// 获取RP详情
  getRpInfo() async {
    var result =
        await PrescribeHttp.getRpTemplate(widget.parameters.getString('rpID'));
    if (result.isSuccess) {
      rp = result.data;
      getOrgInfo(result.data.doctorOrgID);
    } else {
      ToastUtil.error(result.error.msg);
      Routers.pop(context);
    }
  }

  void doRefresh() {
    setState(() {});
  }
}
